<template>
  <div class="userInfo">
    <div class="top">
      <el-button type="text" icon="el-icon-back" @click="goBackPage"
        >返回</el-button
      >
      <span class="title">账号设置</span>
    </div>
    <el-row class="content">
      <el-col class="h100" :span="12" style="padding: 10px 10px 80px 10px; overflow: auto">
        <dividerTitle
          title="个人信息"
          :noBackground="true"
          :fontSize="18"
        ></dividerTitle>
        <label style="margin-left: 60px">头像:</label>
        <div class="showImg">
          <div class="avatar">
            <img :src="imageUrl" alt="" v-if="imageUrl" />
            <span v-else class="text">{{ userFormData.name }}</span>
          </div>
          <div class="avatarBtn">
            <el-button size="mini" @click="updateAvatar">修改头像</el-button>
          </div>
        </div>
        <div class="tip"><span>仅支持jpg, png格式的图片，不大于100k</span></div>
        <editForm
          :formConfig="userConfig"
          ref="userForm"
          :formData="userFormData"
        >
        </editForm>
        <div class="param">
          <label class="desc">岗位</label>
          <div class="list">
            <span
              class="item"
              v-for="(item, index) in postUserVoList"
              :key="index"
            >
              {{ item }}
            </span>
          </div>
        </div>
        <div>
          <el-button
            type="primary"
            size="mini"
            class="btn"
            style="margin-top: 10px"
            @click="saveUser"
            >保存</el-button
          >
        </div>
      </el-col>
      <el-col class="h100 content-right" :span="12">
        <div class="updatePass">
          <dividerTitle
            title="修改签名密码"
            :noBackground="true"
            :fontSize="18"
          ></dividerTitle>
          <editForm
            :formConfig="passwordConfig"
            ref="passwordForm"
            :formData="passwordFormData"
          ></editForm>
          <el-button
            type="primary"
            size="mini"
            class="btn"
            @click="savePassword"
            >保存</el-button
          >
        </div>
        <div class="entrust">
          <dividerTitle
            title="委托"
            :noBackground="true"
            :fontSize="18"
          ></dividerTitle>
          <editForm
            :formConfig="entrustConfig"
            ref="entrustForm"
            :formData="entrustFormData"
          ></editForm>
          <el-button
            type="primary"
            size="mini"
            class="btn"
            @click="goEntrustManage"
            >管理委托</el-button
          >
        </div>
      </el-col>
    </el-row>
    <input
      type="file"
      ref="uploadFile"
      style="display: none"
      accept=".png,.jpg"
      :multiple="false"
      @change="autoUploadFile"
    />
  </div>
</template>

<script>
import {
  getUserDataByAccount,
  addOrEditUser,
  resetPassword,
  queryAgentInfo,
} from "@/api/systemManagement/userManagement.js";
import { verifyStaffInfo } from "@/api/twoTicketManagement/workTicket.js";
export default {
  data() {
    return {
      imageUrl: null,
      photo: null,
      userConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "用户名",
            prop: "name",
            type: "text",
            disabled: true,
            span: 14,
          },
          {
            label: "账号",
            prop: "account",
            type: "text",
            disabled: true,
            span: 14,
          },
          {
            label: "手机号",
            prop: "phone",
            type: "text",
            disabled: true,
            span: 14,
          },
          {
            label: "默认组织",
            prop: "defaultOrgId",
            type: "select",
            span: 14,
            selectOption: this.$store.getters.orgList,
            methods: (val, formData) => {
              let appUserOrgPos = formData.orgVoList.map((item) => {
                let obj = {
                  account: this.userFormData.account,
                  orgId: item.id,
                };
                obj.defaultFlag = item.id == val.value ? 1 : 0;
                return obj;
              });
              this.$refs.userForm.setFormItem("appUserOrgPos", appUserOrgPos);
            },
          },
          {
            label: "默认租户",
            prop: "defaultAppId",
            type: "select",
            span: 14,
            selectOption: this.$store.getters.mineAppList,
            methods: (val, formData) => {
              formData.defaultAppId = val.value;
            },
          },
        ],
      },
      userFormData: {
        jobList: [
          "工作票签发人",
          "工作许可人",
          "运行值班员",
          "站长",
          "机电副总",
          "旁站监理",
        ],
      },
      passwordConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "旧密码",
            prop: "oldPassword",
            type: "password",
            required: true,
            span: 14,
            rules: {
              trigger: "blur",
              validator: (rule, value, callback) => {
                this.checkPassword(rule, value, callback);
              },
            },
          },
          {
            label: "新密码",
            prop: "newPassword",
            type: "text",
            span: 14,
            required: true,
            rules: {
              message:
                "密码必须是包含字母、数字、特殊符号(包含下划线)的8位以上组合",
              trigger: "blur",
              validator: (rule, value, callback) => {
                const mailReg =
                  /^(?![A-Za-z0-9]+$)(?![A-Za-z\W]+$)[a-zA-Z0-9_\W]{8,}$/;
                if (!mailReg.test(value) && value) {
                  return callback(
                    new Error(
                      "密码必须是包含字母、数字、特殊符号(包含下划线)的8位以上组合"
                    )
                  );
                } else {
                  callback();
                }
              },
            },
          },
          {
            label: "确认新密码",
            prop: "newPasswordAgin",
            type: "password",
            span: 14,
            required: true,
            rules: {
              trigger: "blur",
              validator: (rule, value, callback) => {
                this.checkNewPassword(rule, value, callback);
              },
            },
            methods: (val, formData) => {
              this.passwordFormData.newPassword = formData.newPassword;
            },
            focusMethod: (itemArr, formData) => {
              if (formData.newPassword == "") {
                this.$message.warning("请先输入新密码");
              }
            },
          },
        ],
      },
      passwordFormData: {},
      entrustConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "我的委托人",
            prop: "myEntrust",
            type: "text",
            span: 14,
            disabled: true,
          },
          {
            label: "我的被委托人",
            prop: "myEntrusted",
            type: "text",
            span: 14,
            disabled: true,
          },
        ],
      },
      entrustFormData: {},
      postUserVoList: [],
      photoFile: null,
    };
  },
  created() {
    this.getUserInfo(this.$store.getters.mineUserInfo.account);
    this.getEntrusInfo();
  },
  methods: {
    //获取个人信息
    getUserInfo(val) {
      getUserDataByAccount({ account: val }).then((res) => {
        let data = res.data;
        this.getImgUrl(res.data.photo);
        let orgOption = data.orgVoList.map((item) => {
          const obj = {
            label: `${item.levelPathName}/${item.name}`,
            value: item.id,
          };
          return obj;
        });
        this.$set(this.userConfig.itemArr[3], "selectOption", orgOption);
        let defaultOrg = data.orgVoList.filter((item) => item.defaultFlag == 1);
        data.defaultOrgId = defaultOrg.length != 0 ? defaultOrg[0].id : "";
        let appOption = data.appSimpleBeanList.map((item) => {
          const obj = {
            label: item.appName,
            value: item.appMark,
          };
          return obj;
        });
        this.$set(this.userConfig.itemArr[4], "selectOption", appOption);
        data.jobList = [
          "工作票签发人",
          "工作许可人",
          "运行值班员",
          "站长",
          "机电副总",
          "旁站监理",
        ];
        this.userFormData = data;
        this.postUserVoList = data.postUserVoList
          ? data.postUserVoList.map((item) => {
              return item.postName;
            })
          : [];
      });
    },
    //通过photo获取图片地址
    async getImgUrl(id) {
      if (id) {
        this.imageUrl = await this.$utils.echoImg(id);
      }
    },
    //获取委托人信息
    async getEntrusInfo() {
      let res = await queryAgentInfo({
        leader: this.$store.getters.mineUserInfo.account,
      });
      let obj = {};
      obj.myEntrust = res.data.map((item) => item.agentName).join(", ");
      obj.myEntrusted = this.$store.getters.mineUserInfo.leaderUserVos
        .map((item) => item.leaderName)
        .join(", ");
      this.entrustFormData = obj;
    },
    //跳转到委托管理页面
    goEntrustManage() {
      this.$router.push({
        path: "/entrustManage",
      });
    },
    //返回上一个页面
    goBackPage() {
      this.$router.go(-1);
    },
    //检验旧密码
    async checkPassword(rule, val, callback) {
      let params = {
        account: this.userFormData.account,
      };
      params.password = await this.$utils.encryptPassword(val);
      verifyStaffInfo(params)
        .then((res) => {
          callback();
        })
        .catch((e) => {
          return callback(new Error("请输入正确的密码"));
        });
    },
    //校验新密码与确认密码是否一致
    checkNewPassword(rule, val, callback) {
      let newPassword = this.$refs.passwordForm.getFormItem("newPassword");
      if (newPassword != val) {
        //debugger
        return callback(new Error("密码前后不一致"));
      } else {
        callback();
      }
    },
    //保存新的密码
    async savePassword() {
      try {
        let formData = await this.$refs.passwordForm.getFormData();
        let param = {
          account: this.userFormData.account,
        };
        param.password = await this.$utils.encryptPassword(
          formData.newPassword
        );
        param.prePassword = await this.$utils.encryptPassword(
          formData.oldPassword
        );
        let res = await resetPassword(param);
        this.$message.success(res.description);
      } catch (error) {}
    },
    //修改用户头像
    updateAvatar() {
      const fileObj = this.$refs.uploadFile;
      fileObj.click();
    },
    //获取选择的图片
    autoUploadFile(e, file) {
      this.photoFile = this.$refs.uploadFile.files[0];
      console.log(photoFile.size);
      this.imageUrl = URL.createObjectURL(this.photoFile);
    },
    //保存用户信息
    async saveUser() {
      try {
        let data = await this.$refs.userForm.getFormData();
        delete data.userOwnJurisdictionBean;
        delete data.levelPath;
        delete data.levelPathName;
        delete data.orgVoList;
        delete data.appSimpleBeanList;
        if (this.photoFile) {
          this.delPhotoId = data.photo;
          data.photo = null;
        }
        const params = {
          delPhotoId: this.delPhotoId,
        };
        const formData = new FormData();
        formData.append("staffBeanStr", JSON.stringify(data));
        let res;
        if (this.photoFile) {
          formData.append("photo", this.photoFile);
          res = await addOrEditUser(params, formData);
        } else {
          res = await addOrEditUser(params, formData);
        }
        this.$message.success(res.description);
        this.$store.dispatch("GetUserInfo");
      } catch (error) {
        this.$message.error(error);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.userInfo {
  width: 100%;
  height: 100%;
  text-align: left;
  background-color: white;
  border: 10px solid #eaf4ff;
  .top {
    text-align: left;
    height: 48px;
    line-height: 48px;
    padding-left: 20px;
    .title {
      margin-left: 10px;
      font-size: 16px;
      font-weight: 400;
    }
  }
  .content {
    border-top: 10px solid #eaf4ff;
    height: calc(100% - 48px);
    .showImg {
      display: flex;
      //width: 80px;
      flex-direction: column;
      margin-left: 100px;
      .avatar {
        width: 80px;
        height: 80px;
        background: #c7ddff;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        img {
          width: 80px;
          height: 80px;
          overflow: hidden;
          border-radius: 50%;
        }
        .text {
          font-size: 18px;
          font-weight: 400;
          color: #ffffff;
        }
      }
      .avatarBtn {
        width: 80px;
        margin-top: 10px;
      }
    }
    .tip {
      margin: 10px 0 10px 100px;
    }
    .param {
      margin: 10px 10px;
      display: flex;
      .desc {
        height: 40px;
        line-height: 40px;
        font-size: 14px;
        margin: 0 15px 0 50px;
      }
      .item {
        padding: 5px 12px;
        margin: 5px 0;
        text-align: center;
        height: 32px;
        line-height: 32px;
        background-color: #f4f4f4;
        border-radius: 4px;
        margin-right: 15px;
      }
      .list {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
      }
    }
    .content-right {
      border-left: 10px solid #eaf4ff;
      display: flex;
      flex-direction: column;
      .updatePass {
        padding: 10px;
        flex: 1;
      }
      .entrust {
        border-top: 10px solid #eaf4ff;
        padding: 10px;
        flex: 1;
      }
    }
  }
  .btn {
    margin-left: 100px;
  }
}
</style>